const Service = require('egg').Service;
const moment = require('moment');
const Md5 = require('js-md5') 
const UUID = require('uuid-js');

class users extends Service {
  async index(val){
    const { ctx } = this;
    console.log(val);
    const result = await this.app.mysql.select('user',{ 
      columns:['id','phone','userName','nickName','headPortrait','create_time','update_time'],
      orders:[['create_time','desc']],
      limit: Number(val.limit), // 返回数据量
      offset: Number(val.page-1)*Number(val.limit), // 数据偏移量
    });
    const resultNumber = await this.app.mysql.select('user');
    await this.checkSuccess(result);
    return {
      result,
      total:resultNumber.length
    };
  }
  async create(val){
    const { ctx } = this;
    const createUuid = UUID.create().toString();
    const createTime = moment(new Date()).format('YYYY-MM-DD hh:mm:ss');
    const createPassWd = Md5(val.passWord);
    const resultQuery = await this.app.mysql.get('user',{ phone:val.phone });
    if(resultQuery!=null){
      return 2;
    }
    const result = await this.app.mysql.insert('user',{id:createUuid,phone:val.phone,userName:val.userName,passWord:createPassWd,create_time:createTime,headPortrait:val.headPortrait?val.headPortrait:''});
    // console.log(result);  //插入用户数据
    //判断插入成功
    const insertSuccess = result.affectedRows === 1;
    if(insertSuccess){
      return 0;
    }else{
      return 1;
    }
  }
  async update (val,params) {
    const createPassWd = Md5(val.passWord);
    const row = {
      id:params.id,
      userName:val.userName,
      phone:val.phone,
      passWord:createPassWd,
    }
    const { ctx } = this;
    const result = await this.app.mysql.update('user',row);
    //判断更新成功
    const updateSuccess = result.affectedRows === 1;
    if(updateSuccess){
      return 0;
    }else{
      return 1;
    }
  }
  async destroy (params) {
    const result = await this.app.mysql.delete('user',{ id:params.id });
    const deleteSucc = result.affectedRows === 1;
    if(deleteSucc){
      return result;
    }else{
      return 1;
    }
  }
    // 封装统一的调用检查函数，可以在查询、创建和更新等 Service 中复用
    checkSuccess(result) {
      if(result!==null){
        if ( result.errno && result.code) {
          const errorMsg = result && result.error_msg ? result.error_msg : 'unknown error';
          this.ctx.throw(result, errorMsg,result);
        }else{
          return result;
        }
      }else{
        return result;
      }
    }
}

module.exports = users;